package com.sltx.controller.base;



import com.sltx.error.BusinessException;
import com.sltx.error.EmBusinessError;
import com.sltx.response.CommonReturnType;
import com.sltx.util.PageData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;


@Component
@Configuration
@EnableScheduling
public class BaseController implements Serializable{

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	private static final long serialVersionUID = 6357869213649815390L;

	//定义exceptionhandler解决未被controller层吸收的exception
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Object handlerException(HttpServletRequest request, Exception ex){

		Map<String,Object> responseData = new HashMap<String,Object>();

		if(ex instanceof BusinessException){
			BusinessException businessException = (BusinessException) ex;
			responseData.put("errorCode",businessException.getErrorCode());
			responseData.put("errorMsg",businessException.getErrorMsg());
		}else{
			responseData.put("errorCode", EmBusinessError.UNKONW_ERROR.getErrorCode());
			responseData.put("errorMsg",EmBusinessError.UNKONW_ERROR.getErrorMsg());
		}
		return  CommonReturnType.create(responseData,"fail");
	}

	/**
	 * 得到PageData
	 */


	public PageData getPageData(){
		return new PageData(this.getRequest());
	}
	
	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView(){
		return new ModelAndView();
	}
	
	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}


	

	
	public static void logBefore(Logger logger, String interfaceName){
		logger.info("");
		logger.info("start");
		logger.info(interfaceName);
	}
	
	public static void logAfter(Logger logger){
		logger.info("end");
		logger.info("");
	}



}
